﻿namespace Smart.Navigation.Windows.ViewModels
{
    using System;
    using System.Windows;
    using System.Windows.Controls;

    /// <summary>
    /// ViewModelビュープロバイダー
    /// </summary>
    public class ViewModelViewProvider : IViewProvider
    {
        private readonly ContentControl parent;

        /// <summary>
        /// 非同期
        /// </summary>
        public bool IsAsync
        {
            get { return false; }
        }

        /// <summary>
        /// コンストラクタ
        /// </summary>
        /// <param name="parent">親コントロール</param>
        public ViewModelViewProvider(ContentControl parent)
        {
            this.parent = parent;
        }

        /// <summary>
        /// イベントターゲット解決
        /// </summary>
        /// <param name="view">ビューインスタンス</param>
        /// <returns>ターゲット</returns>
        public object ResolveEventTarget(object view)
        {
            var element = view as FrameworkElement;
            return element != null ? element.DataContext : view;
        }

        /// <summary>
        /// 非同期処理実行
        /// </summary>
        /// <param name="method">メソッド</param>
        /// <param name="args">引数</param>
        public void BeginInvoke(Delegate method, params object[] args)
        {
            parent.Dispatcher.BeginInvoke(method, args);
        }

        /// <summary>
        /// ビュー作成
        /// </summary>
        /// <param name="type">型</param>
        /// <returns>ビューインスタンス</returns>
        public object ViewCreate(Type type)
        {
            var view = Activator.CreateInstance(type);

            parent.Content = view;

            return view;
        }

        /// <summary>
        /// ビュー活性化
        /// </summary>
        /// <param name="view">ビューインスタンス</param>
        public void ViewActive(object view)
        {
            var element = (UIElement)view;
            if (element != null)
            {
                element.Visibility = Visibility.Visible;
                element.Focus();
            }
        }

        /// <summary>
        /// ビュー非活性化
        /// </summary>
        /// <param name="view">ビューインスタンス</param>
        public void ViewDeactive(object view)
        {
            var element = (UIElement)view;
            if (element != null)
            {
                element.Visibility = Visibility.Hidden;
            }
        }

        /// <summary>
        /// ビュー破棄
        /// </summary>
        /// <param name="view">ビューインスタンス</param>
        public void ViewDispose(object view)
        {
        }
    }
}
